package com.shqcjd.siemensglass.ui.remote;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.shqcjd.siemensglass.MyApp;
import com.shqcjd.siemensglass.R;
import com.shqcjd.siemensglass.adapter.ImageAdapter;
import com.shqcjd.siemensglass.bean.ImageBean;
import com.shqcjd.siemensglass.bean.RoomUserEntity;
import com.shqcjd.siemensglass.http.ApiManager;
import com.shqcjd.siemensglass.http.BaseResult;
import com.shqcjd.siemensglass.http.Response;
import com.shqcjd.siemensglass.http.ResponseData;
import com.shqcjd.siemensglass.http.RxHttp;
import com.shqcjd.siemensglass.ui.InvitationListActivity;
import com.shqcjd.siemensglass.utils.GlobalParams;
import com.shqcjd.siemensglass.utils.SpaceItemDecoration;
import com.shqcjd.siemensglass.utils.Utils;
import com.shqcjd.siemensglass.widget.SaveDraftDialog;
import com.shqcjd.siemensglass.widget.whiteboard.BoardmageLoader;
import com.shqcjd.siemensglass.widget.whiteboard.DeveloperInfo;

import org.ar.arboard.boardevent.ARBoardListener;
import org.ar.arboard.utils.ARBoardConfig;
import org.ar.arboard.weight.ARBoardView;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import es.dmoral.toasty.Toasty;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.mediaio.IVideoFrameConsumer;
import io.agora.rtc.video.VideoCanvas;
import io.agora.rtc.video.VideoEncoderConfiguration;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class VideoChatViewActivity extends AppCompatActivity implements IVideoFrameConsumer, MyApp.OnAgoraEngineInterface {

    private static final String LOG_TAG = VideoChatViewActivity.class.getSimpleName();

    private static final int PERMISSION_REQ_ID_RECORD_AUDIO = 22;
    private static final int PERMISSION_REQ_ID_CAMERA = PERMISSION_REQ_ID_RECORD_AUDIO + 1;

    private RtcEngine mRtcEngine;// Tutorial Step 1
    private Context mContext;

    private boolean isFirst = true;

//    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() { // Tutorial Step 1
//        @Override
//        public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) { // Tutorial Step 5
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
////                    setupRemoteVideo(uid);
//                }
//            });
//        }
//
//        @Override
//        public void onUserJoined(int uid, int elapsed) {
//            super.onUserJoined(uid, elapsed);
//            userNum++;
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    getRoomUserNum();
//                }
//            });
//
//        }
//
//        //用户退出时
//        @Override
//        public void onUserOffline(int uid, int reason) { // Tutorial Step 7
//            userNum--;
//            if (userNum == 0) {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        AlertDialog dialog = new AlertDialog.Builder(VideoChatViewActivity.this)
//                                .setTitle("")   //R.string.vt_dialog_logout_title
//                                .setMessage("对方已离开!")
//                                .setPositiveButton(R.string.vt_dialog_btn_positive, new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        onRemoteUserLeft();
//                                    }
//                                })
//                                .setNegativeButton(R.string.vt_dialog_btn_cancel, new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        // Nothing to do
//                                    }
//                                })
//                                .create();
//                        if (!isFinishing()) {
//                            dialog.show();
//                        }
//
//
//                    }
//                });
//            }
//
//        }
//
//        @Override
//        public void onUserMuteVideo(final int uid, final boolean muted) { // Tutorial Step 10
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
////                    onRemoteUserVideoMuted(uid, muted);
//                }
//            });
//        }
//
//
//        //检测网络
//
//        /**
//         * QUALITY_UNKNOWN(0)：质量未知
//         QUALITY_EXCELLENT(1)：质量极好
//         QUALITY_GOOD(2)：用户主观感觉和极好差不多，但码率可能略低于极好
//         QUALITY_POOR(3)：用户主观感受有瑕疵但不影响沟通
//         QUALITY_BAD(4)：勉强能沟通但不顺畅
//         QUALITY_VBAD(5)：网络质量非常差，基本不能沟通
//         QUALITY_DOWN(6)：完全无法沟通
//         * @param uid
//         * @param txQuality
//         * @param rxQuality
//         */
//        @Override
//        public void onNetworkQuality(int uid, int txQuality, int rxQuality) {
//            super.onNetworkQuality(uid, txQuality, rxQuality);
//            Logger.i("网络检测" + uid + "  " + txQuality + "  " + rxQuality);
//            //0为本地用户
//            if (uid == 0) {
//                if (txQuality >= 3 || rxQuality >= 3) {
////                    Toasty.info(VideoChatViewActivity.this,"当前网络似乎不太好").show();
//                    iv_network.setBackground(getResources().getDrawable(R.drawable.shape_color_btn_red));
//                } else {
//                    iv_network.setBackground(getResources().getDrawable(R.drawable.shape_color_btn_green));
//                }
//            }
//        }
//    };

    @Override
    public void onFirstRemoteVideoDecoded(int uid, int width, int height, int elapsed) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                    setupRemoteVideo(uid);
            }
        });
    }

    @Override
    public void onUserJoined(int uid, int elapsed) {
        userNum++;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                getRoomUserNum();
            }
        });
        startRoomHttp();
    }

    @Override
    public void onUserOffline(int uid, int reason) {
        userNum--;
        if (userNum == 0) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    AlertDialog dialog = new AlertDialog.Builder(VideoChatViewActivity.this)
//                            .setTitle("")   //R.string.vt_dialog_logout_title
//                            .setMessage("对方已离开!")
//                            .setPositiveButton(R.string.vt_dialog_btn_positive, new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    onRemoteUserLeft();
//                                }
//                            })
//                            .setNegativeButton(R.string.vt_dialog_btn_cancel, new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    // Nothing to do
//                                }
//                            })
//                            .create();
//                    if (!isFinishing()) {
//                        dialog.show();
//                    }
                    Toasty.info(mContext,"对方已离开!", Toast.LENGTH_SHORT).show();
                    finish();


                }
            });
        }
    }

    @Override
    public void onUserMuteVideo(int uid, boolean muted) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                    onRemoteUserVideoMuted(uid, muted);
            }
        });
    }

    @Override
    public void onJoinChannelSuccess(String channel, int uid, int elapsed) {

    }

    /**
     * QUALITY_UNKNOWN(0)：质量未知
     * QUALITY_EXCELLENT(1)：质量极好
     * QUALITY_GOOD(2)：用户主观感觉和极好差不多，但码率可能略低于极好
     * QUALITY_POOR(3)：用户主观感受有瑕疵但不影响沟通
     * QUALITY_BAD(4)：勉强能沟通但不顺畅
     * QUALITY_VBAD(5)：网络质量非常差，基本不能沟通
     * QUALITY_DOWN(6)：完全无法沟通
     *
     * @param uid
     * @param txQuality
     * @param rxQuality
     */
    @Override
    public void onNetworkQuality(int uid, int txQuality, int rxQuality) {
        Logger.i("网络检测" + uid + "  " + txQuality + "  " + rxQuality);
        //0为本地用户
        if (uid == 0) {
            if (txQuality >= 3 || rxQuality >= 3) {
//                    Toasty.info(VideoChatViewActivity.this,"当前网络似乎不太好").show();
                iv_network.setBackground(getResources().getDrawable(R.drawable.shape_color_btn_red));
            } else {
                iv_network.setBackground(getResources().getDrawable(R.drawable.shape_color_btn_green));
            }
        }
    }


    private String channelName;
    private String account;
    private String myAccount;
    private AgoraAPIOnlySignal mAgoraAPI;
    private RecyclerView rv_screenshot_list;
    private TextView tv_name;
    private String guidName;
    private ImageAdapter imageAdapter;
    private List<ImageBean> imageList = new ArrayList<>();
    private ImageView iv_big_img;
    private ImageView iv_network;
    private RelativeLayout rl_invitation_user;
    private int userNum = 0;//当前频道总人数
    private ImageButton ib_back;
    private ARBoardView any_board;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        //去除title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //去掉Activity上面的状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_video_chat_view);
        initView();
        initData();
        if (checkSelfPermission(Manifest.permission.RECORD_AUDIO, PERMISSION_REQ_ID_RECORD_AUDIO) && checkSelfPermission(Manifest.permission.CAMERA, PERMISSION_REQ_ID_CAMERA)) {
            initAgoraEngineAndJoinChannel();
        }


    }

    /**
     * 初始化白板
     */
    private void initWhiteboard() {
        //设置画板监听回调
        any_board.setWhiteBoardListener(new ARBoardListener() {
            @Override
            public void initBoardSuccess() {
                Logger.i("白板:initBoardSuccess");
            }

            @Override
            public void onBoardError(int nErrorCode) {
                Logger.i("白板:onBoardError:" + nErrorCode);
            }

            @Override
            public void onBoardServerDisconnect() {
                Logger.i("白板:onBoardServerDisconnect");
            }

            @Override
            public void onBoardPageChange(int currentPage, int totlePage, String backgroundUrl) {
                Logger.i("白板:onBoardPageChange");
            }

            @Override
            public void onBoardDrawsChangeTimestamp(long timestamp) {
                Logger.i("白板:onBoardDrawsChangeTimestamp:" + timestamp);
            }

            @Override
            public void onBoardMessage(String msgData) {
                Logger.i("白板:onBoardMessage" + msgData);
            }

            @Override
            public void onBoardDestroy() {
                Logger.i("白板:onBoardDestroy");
            }
        });
        //设置图片加载器
        any_board.setImageLoader(new BoardmageLoader());
        List<String> boardImageList = new ArrayList<>();
        boardImageList.add(DeveloperInfo.IMAGE1);
//        boardImageList.add("#00000000");//纯色背景添加这个格式的颜色代码
        String roomString = channelName.replaceAll("-", "");
        String roomId = roomString.substring(roomString.length() - 10);
        Logger.i("白板id: initWithRoomId 1:"+roomId+" 2:"+roomId+" 3:"+GlobalParams.getUserId()+" 4:"+boardImageList);
        //初始化画板
        any_board.initWithRoomId(roomId, roomId, GlobalParams.getUserId() + "", boardImageList);
        //设置画笔类型
        any_board.getARBoardConfig().setBrushModel(ARBoardConfig.BrushModel.Transform);
    }


    private void setBoardLayout() {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) any_board.getLayoutParams(); //取控件mRlVideoViewLayout当前的布局参数
        final float height = this.getResources().getDisplayMetrics().heightPixels;
        final double width = height * 1.777777;//16:9
        // int height = (int) (0.56 * screenWidth);
        params.width = (int) width;// 强制设置控件的大小
        any_board.setLayoutParams(params); //使设置好的布局参数应用到控件
        any_board.requestLayout();
        any_board.cleanCurrentDraw();

    }

    private void leavewhiteBoard() {
        any_board.leave();
    }

    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    StringBuilder stringBuilder = new StringBuilder("");

    /**
     * 获取房间内指导人数
     */
    private void getRoomUserNum() {
        String roomId = GlobalParams.getRoomId();
        new RxHttp<BaseResult<List<RoomUserEntity>>>().send(ApiManager.getService().getRoomUser(roomId), new Response<BaseResult<List<RoomUserEntity>>>(this) {
            @Override
            public void onNext(BaseResult<List<RoomUserEntity>> result) {
                super.onNext(result);
                if (result.code == 0 && result.data != null) {//正确
                    stringBuilder.delete(0, stringBuilder.length());
                    stringBuilder.append("当前指导者:");
                    for (int i = 0; i < result.data.size(); i++) {
                        RoomUserEntity entity = result.data.get(i);
                        if (entity.name.equals("AR眼镜操作员")) {
                            continue;
                        }
                        stringBuilder.append(entity.name);
                        if (i < result.data.size() - 2) {
                            stringBuilder.append(",");
                        }
                    }
                    tv_name.setText(stringBuilder.toString());
                    tv_name.setSelected(true);
                }
            }
        });
    }

    private void initView() {
        any_board = findViewById(R.id.any_board);
        iv_network = findViewById(R.id.iv_network);
        iv_big_img = findViewById(R.id.iv_big_img);
        rv_screenshot_list = findViewById(R.id.rv_screenshot_list);
        tv_name = findViewById(R.id.tv_name);
        rl_invitation_user = findViewById(R.id.rl_invitation_user);
        ib_back = findViewById(R.id.ib_back);
        ib_back.setNextFocusDownId(R.id.rl_invitation_user);
        rl_invitation_user.setNextFocusUpId(R.id.ib_back);
        rl_invitation_user.setNextFocusLeftId(R.id.rl_invitation_user);
        rl_invitation_user.setNextFocusDownId(R.id.rl_invitation_user);

        imageAdapter = new ImageAdapter(imageList, this);
        rv_screenshot_list.setLayoutManager(new LinearLayoutManager(this));
        rv_screenshot_list.addItemDecoration(new SpaceItemDecoration(0, 10));
        rv_screenshot_list.setAdapter(imageAdapter);
        imageAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        imageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //更新item状态
                ImageBean item = (ImageBean) adapter.getItem(position);
                item.isShow = true;
                adapter.notifyItemChanged(position);

                RequestOptions options = new RequestOptions();
                options.placeholder(R.mipmap.ic_loading);//图片加载出来前，显示的图片
                /*显示大图*/
                if (iv_big_img.getVisibility() != View.VISIBLE) {
                    Glide.with(VideoChatViewActivity.this).load(item.url).apply(options).into(iv_big_img);
                    iv_big_img.setVisibility(View.VISIBLE);
                } else {
                    iv_big_img.setVisibility(View.GONE);
                }

//                Intent intent = new Intent(VideoChatViewActivity.this,BigImageActivity.class);
//                intent.putExtra("ImageUrl", item.url);
//                startActivity(intent);
            }
        });

        rl_invitation_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(VideoChatViewActivity.this, InvitationListActivity.class);
                startActivity(it);
            }
        });

    }


    private void initData() {
        channelName = getIntent().getStringExtra("channelName");
        account = getIntent().getStringExtra("account");
        guidName = getIntent().getStringExtra("guidName");
        myAccount = Utils.getAndroidId(this);

        tv_name.setText("当前指导者:" + guidName);
    }

    /**
     * 点击大图关闭
     *
     * @param view
     */
    public void onClickBigImg(View view) {
        if (view.getVisibility() == View.VISIBLE) {
            view.setVisibility(View.GONE);
        }
    }


    private void initAgoraEngineAndJoinChannel() {
        //初始化信令
        mAgoraAPI = MyApp.the().getmAgoraAPI();
        //初始化视频
        initializeAgoraEngine();     // Tutorial Step 1
        setupVideoProfile();         // Tutorial Step 2
        setupLocalVideo();           // Tutorial Step 3
        joinChannel();               // Tutorial Step 4

        initWhiteboard();
    }


    /**
     * 当用户离开
     */
    // Tutorial Step 7
    private void onRemoteUserLeft() {

        Map<String, String> map = new HashMap<>();
        map.put("id", channelName);
        String json = new Gson().toJson(map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        //结束远程指导
//        new RxHttp<BaseResult>().send(ApiManager.getService().endVideo(requestBody),new Response<BaseResult>(this));


        finish();

    }


    public boolean checkSelfPermission(String permission, int requestCode) {
        Log.i(LOG_TAG, "checkSelfPermission " + permission + " " + requestCode);
        if (ContextCompat.checkSelfPermission(this,
                permission)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{permission},
                    requestCode);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @NonNull int[] grantResults) {
        Log.i(LOG_TAG, "onRequestPermissionsResult " + grantResults[0] + " " + requestCode);

        switch (requestCode) {
            case PERMISSION_REQ_ID_RECORD_AUDIO: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkSelfPermission(Manifest.permission.CAMERA, PERMISSION_REQ_ID_CAMERA);
                } else {
                    showLongToast("No permission for " + Manifest.permission.RECORD_AUDIO);
                    finish();
                }
                break;
            }
            case PERMISSION_REQ_ID_CAMERA: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initAgoraEngineAndJoinChannel();
                } else {
                    showLongToast("No permission for " + Manifest.permission.CAMERA);
                    finish();
                }
                break;
            }
        }
    }

    public final void showLongToast(final String msg) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        });
    }


    // Tutorial Step 10
    public void onLocalVideoMuteClicked(View view) {
        ImageView iv = (ImageView) view;
        if (iv.isSelected()) {
            iv.setSelected(false);
            iv.clearColorFilter();
        } else {
            iv.setSelected(true);
            iv.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
        }
        //暂停本地视频流 true: 不发送本地视频流 false: 发送本地视频流
        mRtcEngine.muteLocalVideoStream(iv.isSelected());

        FrameLayout container = (FrameLayout) findViewById(R.id.local_video_view_container);
        SurfaceView surfaceView = (SurfaceView) container.getChildAt(0);
        surfaceView.setZOrderMediaOverlay(!iv.isSelected());
        surfaceView.setVisibility(iv.isSelected() ? View.GONE : View.VISIBLE);
    }

    // Tutorial Step 9
    public void onLocalAudioMuteClicked(View view) {
        ImageView iv = (ImageView) view;
        if (iv.isSelected()) {
            iv.setSelected(false);
            iv.clearColorFilter();
        } else {
            iv.setSelected(true);
            iv.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
        }

        mRtcEngine.muteLocalAudioStream(iv.isSelected());
    }

    // Tutorial Step 8
    public void onSwitchCameraClicked(View view) {
        mRtcEngine.switchCamera();
    }

    // Tutorial Step 6
    public void onEncCallClicked(View view) {
//        AlertDialog dialog = new AlertDialog.Builder(VideoChatViewActivity.this)
//                .setTitle("")   //R.string.vt_dialog_logout_title
//                .setMessage("确认离开？")
//                .setPositiveButton(R.string.vt_dialog_btn_positive, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
////                        finish();
//                        leaveChannel();
//                    }
//                })
//                .setNegativeButton(R.string.vt_dialog_btn_cancel, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        // Nothing to do
//                    }
//                })
//                .create();
//        dialog.show();
        SaveDraftDialog saveDraftDialog = new SaveDraftDialog(mContext);
        saveDraftDialog.setOnDialogCommit(new SaveDraftDialog.OnDialogCommit() {
            @Override
            public void onDialogCommitClick() {
                        leaveChannel();
            }
        });
        saveDraftDialog.show();

    }

    // Tutorial Step 1
    private void initializeAgoraEngine() {
        try {
            Logger.i("ok------------1");
//            mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRtcEventHandler);
            mRtcEngine = MyApp.the().getmRtcEngine();
            MyApp.the().setOnAgoraEngineInterface(this);
        } catch (Exception e) {
            Log.e(LOG_TAG, Log.getStackTraceString(e));

            throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
        }
    }

    // Tutorial Step 2
    private void setupVideoProfile() {
        mRtcEngine.enableVideo();
//        mRtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_360P, false);//视频分辨率


        VideoEncoderConfiguration.VideoDimensions vd_1280x720 = VideoEncoderConfiguration.VD_1280x720;
        VideoEncoderConfiguration.FRAME_RATE frameRateFps15 = VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15;
        int standardBitrate = VideoEncoderConfiguration.STANDARD_BITRATE;
        VideoEncoderConfiguration.ORIENTATION_MODE orientationModeAdaptive = VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_LANDSCAPE;
        VideoEncoderConfiguration videoEncoderConfiguration = new VideoEncoderConfiguration(vd_1280x720, frameRateFps15, standardBitrate, orientationModeAdaptive);
        mRtcEngine.setVideoEncoderConfiguration(videoEncoderConfiguration);
    }

    // Tutorial Step 3
    private void setupLocalVideo() {
        FrameLayout container = (FrameLayout) findViewById(R.id.local_video_view_container);
        //todo
        SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());
        surfaceView.setZOrderMediaOverlay(true);
        container.addView(surfaceView);
        //设置本地视频视频
        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, 0));
        //镜像问题调用
        mRtcEngine.setParameters("{\"che.video.localViewMirrorSetting\":\"disableMirror\"}");
        mRtcEngine.startPreview();
        //转换摄像头
        mRtcEngine.switchCamera();

    }

    // Tutorial Step 4

    /**
     * joinChannel(String token,String channelName,String optionalInfo,int optionalUid);
     * channelName 房间名 同一房间代表同一通话
     * optionalInfo 房间信息
     * optionalUid 用户id
     */
    private void joinChannel() {
        int userId = GlobalParams.getUserId();
        Logger.i("channelName：" + channelName + " userId:" + userId);
        mRtcEngine.joinChannel(null, channelName, "Extra Optional Data", userId); // if you do not specify the uid, we will generate the uid for you
    }


    //退出
    // Tutorial Step 6
    private void leaveChannel() {
        //用户必须调用 leaveChannel() 方法退出当前通话，才能进入下一个频道。
        endRoomHttp();
    }

    private void endRoomHttp() {
        Log.e("tou", GlobalParams.getRoomId() + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        new RxHttp<BaseResult>().send(ApiManager.getService().endVideo(GlobalParams.getRoomId()), new Response<BaseResult>(VideoChatViewActivity.this) {
            @Override
            public void onNext(BaseResult result) {
                super.onNext(result);
                Logger.i("远程指导---结束");
                if (result.code == 0) {
                    finish();
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                Logger.i("远程指导---onError");
                finish();
            }

            @Override
            public void onComplete() {
                super.onComplete();
                Logger.i("远程指导---onComplete");
                finish();
            }
        });
    }

    private void startRoomHttp() {
        new RxHttp<ResponseData>().send(ApiManager.getService().startVideo(GlobalParams.getRoomId()), new Response<ResponseData>(VideoChatViewActivity.this) {
            @Override
            public void onNext(ResponseData result) {
                super.onNext(result);
                Logger.i("开始录制");
                if (result.retCode == 0) {

                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                Logger.i("远程指导---onError");
            }

            @Override
            public void onComplete() {
                super.onComplete();
                Logger.i("远程指导---onComplete");
            }
        });
    }

    //结束呼叫
    private void callOutHangup() {
        if (mAgoraAPI != null)
            mAgoraAPI.channelInviteEnd(channelName, account, 0);
    }

    @Override
    public void onBackPressed() {
//        AlertDialog dialog = new AlertDialog.Builder(this)
//                .setTitle("")   //R.string.vt_dialog_logout_title
//                .setMessage(R.string.vt_dialog_logout_message)
//                .setPositiveButton(R.string.vt_dialog_btn_positive, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        VideoChatViewActivity.super.onBackPressed();
//
//                    }
//                })
//                .setNegativeButton(R.string.vt_dialog_btn_cancel, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        // Nothing to do
//                    }
//                })
//                .create();
//        dialog.show();
        SaveDraftDialog saveDraftDialog = new SaveDraftDialog(mContext);
        saveDraftDialog.setOnDialogCommit(new SaveDraftDialog.OnDialogCommit() {
            @Override
            public void onDialogCommitClick() {
                VideoChatViewActivity.super.onBackPressed();
            }
        });
        saveDraftDialog.show();
    }


    /**
     * 设置声网信令监听
     */
    private void addSignalingCallback() {
        if (mAgoraAPI == null) {
            return;
        }

        mAgoraAPI.callbackSet(new AgoraAPI.CallBack() {


            @Override
            public void onInviteEndByMyself(String channelID, String account, int uid) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        onEndCall();
                    }
                });
            }

            /**
             * 收到频道消息回调
             * @param channelID 频道名
             * @param account 客户端定义的用户账号
             * @param uid 固定填 0
             * @param msg 消息正文
             */
            @Override
            public void onMessageChannelReceive(String channelID, String account, int uid, final String msg) {
                super.onMessageChannelReceive(channelID, account, uid, msg);
                Logger.i("接收到频道图片: account:" + account + " uid:" + uid + " msg:" + msg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //判断集合中图片数量是否>=3
                        if (imageList.size() >= 3) {
                            //数量大于3删除第一个
                            imageAdapter.remove(0);
                            imageAdapter.addData(imageAdapter.getData().size(), new ImageBean(msg));
                            //添加最后一个
                        } else {
                            imageAdapter.addData(imageAdapter.getData().size(), new ImageBean(msg));
                        }
                    }
                });
            }

            //接收到发送过来的信息
            @Override
            public void onMessageInstantReceive(String account, int uid, final String msg) {
                super.onMessageInstantReceive(account, uid, msg);
                Logger.i("接收到图片: account:" + account + " uid:" + uid + " msg:" + msg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //判断集合中图片数量是否>=3
                        if (imageList.size() >= 3) {
                            //数量大于3删除第一个
                            imageAdapter.remove(0);
                            imageAdapter.addData(imageAdapter.getData().size(), new ImageBean(msg));
                            //添加最后一个
                        } else {
                            imageAdapter.addData(imageAdapter.getData().size(), new ImageBean(msg));
                        }
                    }
                });


            }


        });


    }

    private void onEndCall() {
        finish();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(isFirst){
            isFirst = false;
            rl_invitation_user.requestFocus();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setBoardLayout();
        addSignalingCallback();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
                if(rv_screenshot_list.getChildCount()>0){
                    if(imageAdapter.currentPos==0){
                        rl_invitation_user.requestFocus();
                        imageAdapter.currentPos = -2;
                        return true;
                    }
                }

                KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP);
                simulateKey(keyEvent);
                return true;
            }
            else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {
                View rootview = VideoChatViewActivity.this.getWindow().getDecorView();
                View fView = rootview.findFocus();
                if(fView.getId() == R.id.rl_invitation_user){
                    if(rv_screenshot_list.getChildCount()>0){
                        rv_screenshot_list.getChildAt(0).requestFocus();
                        return true;
                    }
                }
                if(imageAdapter.currentPos==rv_screenshot_list.getChildCount()-1){
                    rv_screenshot_list.getChildAt(imageAdapter.currentPos).requestFocus();
                    return true;
                }
                KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN);
                simulateKey(keyEvent);
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    private void simulateKey(final KeyEvent keyCode) {
        new Thread() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void run() {
                try {
                    InputMethodManager systemService = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                    systemService.dispatchKeyEventFromInputMethod(getWindow().getDecorView().getRootView(), keyCode);
                } catch (Exception e) {

                }
            }

        }.start();

    }


    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mRtcEngine.switchCamera();
        mRtcEngine.leaveChannel();
        MyApp.the().getmAgoraAPI().channelLeave(channelName);//离开
//        RtcEngine.destroy();
        mRtcEngine = null;
        leavewhiteBoard();
    }

    @Override
    public void consumeByteBufferFrame(ByteBuffer byteBuffer, int i, int i1, int i2, int i3, long l) {

    }

    @Override
    public void consumeByteArrayFrame(byte[] bytes, int i, int i1, int i2, int i3, long l) {

    }

    @Override
    public void consumeTextureFrame(int i, int i1, int i2, int i3, int i4, long l, float[] floats) {

    }


}
